package com.cxrj.zhsq.userManage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.cxrj.zhsq.userManage.dao.LogMapper;
import com.cxrj.zhsq.userManage.dao.UserMapper;
import com.cxrj.zhsq.userManage.entity.Log;
import com.cxrj.zhsq.userManage.entity.User;
import com.cxrj.zhsq.userManage.service.UserService;
import com.cxrj.zhsq.utils.Encrypt;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	// @Autowired
	// private RoleService roleService;

	@Resource
	private LogMapper logMapper;

	@Override
	public Map<String, Object> login(String account, String password, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;// 0:账号不存在，1:密码错误，2:登录成功

		// 用户名查询
		List<User> user_account = userMapper.selectByCondition(" user_account='" + account + "' and user_status not in ('2') ");
		if (user_account != null && user_account.size() > 0) {
			// 查询密码
			List<User> user_password = userMapper.selectByCondition(" USER_ACCOUNT='" + account + "' AND USER_PASSWORD=md5('" + password + "')  AND USER_STATUS NOT IN ('0') ");
			if (user_password != null && user_password.size() > 0) {
				// 登录成功！保存用账号id和用户名
				request.getSession().setAttribute("userId", user_password.get(0).getUserId());
				request.getSession().setAttribute("userName", user_password.get(0).getUserName());
				request.getSession().setAttribute("userAccount", user_password.get(0).getUserAccount());
				request.getSession().setAttribute("communityName", user_password.get(0).getCommunityName());
				request.getSession().setAttribute("roleId", user_password.get(0).getRoleId());
				resultMap.put("roleId", user_password.get(0).getRoleId());
				Log log = new Log();
				log.setId(UUID.randomUUID().toString());
				log.setLogTime(new Date());
				log.setUserId(user_password.get(0).getUserId());
				log.setProjectId("1");
				log.setLogText("管理后台登入");
				// 保存数据库
				logMapper.insertSelective(log);
				result = 1;// 登录成功
			} else {
				result = 2;// 密码错误
			}
		} else {
			result = 0;// 账号不存在
		}

		resultMap.put("result", result);
		return resultMap;
	}

	@Override
	public Map<String, Object> selectUsersByOrganizationId(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> sqlMap = new HashMap<String, Object>();
		// response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		String draw = "0";
		draw = request.getParameter("draw");
		// 数据起始位置
		String start = request.getParameter("start");
		// 数据长度
		String length = request.getParameter("length");
		// 总记录数
		String recordsTotal = "0";

		// 获取排序方式 默认为asc
		/*
		 * String orderDir = "desc"; orderDir =
		 * request.getParameter("order[0][dir]");
		 */

		sqlMap.put("start", Integer.valueOf(start));
		sqlMap.put("length", Integer.valueOf(length));
		// sqlMap.put("searchVal", request.getParameter("search[value]"));
		sqlMap.put("organizationId", request.getParameter("organizationId"));

		List<User> list = userMapper.select_by_page(sqlMap);
		// 获取数据库总记录数
		recordsTotal = userMapper.get_count(sqlMap) + "";

		resultMap.put("draw", draw);
		resultMap.put("recordsTotal", recordsTotal);
		resultMap.put("recordsFiltered", recordsTotal);
		resultMap.put("data", list);

		return resultMap;
	}

	@Override
	public void insertUser(Map<String, Object> paramMap, HttpServletRequest request) {
		paramMap.put("userId", UUID.randomUUID().toString());
		paramMap.put("userPassword", Encrypt.md5("123456"));
		paramMap.put("userCode", createUserCode());
		paramMap.put("userImp", request.getSession().getAttribute("userId"));
		userMapper.insertSelective(paramMap);
		// roleService.updateUserSet(paramMap);
	}

	public String createUserCode() {
		String userCode = UUID.randomUUID().toString().substring(0, 8);
		List<User> user = userMapper.selectByCondition(" user_code='" + userCode + "'");
		if (user != null && user.size() > 0) {
			userCode = createUserCode();
		}
		return userCode;
	}

	@Override
	public Map<String, Object> selectUserById(String userId) {
		Map<String, Object> user = userMapper.selectUserById(userId);
		/*
		 * List<Map<String, Object>> roles = roleService.selectByUserCode(user);
		 * if (roles != null && roles.size() > 0){
		 * user.put("roleId",roles.get(0).get("roleId")); }
		 */
		return user;
	}

	@Override
	public void updateUserInfo(Map<String, Object> paramMap) {
		userMapper.updateByPrimaryKeySelective(paramMap);
		// roleService.updateUserSet(paramMap);
	}

	@Override
	public void deleteUserById(String userId) {
		userMapper.deleteByPrimaryKey(userId);
	}

	@Override
	public Map<String, Object> selectUserAccount(String userAccount) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<User> user = userMapper.selectByCondition(" user_account='" + userAccount + "'");
		if (user != null && user.size() > 0) {
			resultMap.put("status", "n");
			resultMap.put("info", "用户名已被使用！");
		} else {
			resultMap.put("status", "y");
			resultMap.put("info", "用户名可用！");
		}
		return resultMap;
	}

	@Override
	public void deleteUsers(String[] userIds) {
		userMapper.deleteUsersByIds(userIds);
	}

	@Override
	public Map<String, Object> updatePassword(Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			User user = userMapper.selectByPrimaryKey(String.valueOf(map.get("userId")));
			if (user != null && user.getUserPassword().equals(Encrypt.md5(String.valueOf(map.get("oldPassword"))))) {
				map.put("newPassword", Encrypt.md5(String.valueOf(map.get("newPassword"))));
				userMapper.updatePassword(map);
				resultMap.put("result", 0);
			} else {
				resultMap.put("result", 1);
			}
		} catch (Exception e) {
			resultMap.put("result", -1);
			throw new RuntimeException(e);
		}
		return resultMap;
	}

	@Override
	public void updateUserStatus(Map<String, Object> map) {
		map.put("userStatus", map.get("userStatus").equals("0") ? "1" : "0");
		userMapper.updateUserStatus(map);
	}

	@Override
	public void resetUserPwdById(String userId) {
		userMapper.resetUserPwdById(userId);
	}

	@Override
	public Map<String, Object> selectPwdById(String userId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String pwd = userMapper.selectPwdById(userId);
		if (pwd.equals("123456") || pwd.equals("e10adc3949ba59abbe56e057f20f883e")) {
			resultMap.put("result", 0);
		} else {
			resultMap.put("result", -1);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> selectAppUser(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> sqlMap = new HashMap<String, Object>();
		response.setContentType("text/html;charset=utf-8");
		// 数据起始位置
		String start = request.getParameter("offset");
		// 数据长度
		String length = request.getParameter("limit");
		// 总记录数
		String recordsTotal = "0";
		// 获取数据库总记录数
		String kod = request.getParameter("kod");

		sqlMap.put("start", Integer.parseInt(start));
		if (kod == null || kod == "") {
			sqlMap.put("condition", " where 1=1 ");
			recordsTotal = userMapper.getAppUserCount(" 1=1") + "";
		} else {
			sqlMap.put("condition", "  where  user_mobile like " + '"' + '%' + kod + '%' + '"' + " or user_name like " + '"' + '%' + kod + '%' + '"' + " or user_sex like " + '"' + '%' + kod + '%'
					+ '"' + " or community_name like " + '"' + '%' + kod + '%' + '"' + " ");
			recordsTotal = userMapper.getAppUserCount("user_mobile like " + '"' + '%' + kod + '%' + '"' + " or user_name like " + '"' + '%' + kod + '%' + '"' + " or user_sex like " + '"' + '%' + kod
					+ '%' + '"' + " or community_name like " + '"' + '%' + kod + '%' + '"' + "") + "";
		}

		sqlMap.put("length", Integer.parseInt(length));
		List<Map<String, Object>> list = userMapper.selectAppUserPager(sqlMap);

		// Iterator<Map<String, Object>> it = list.listIterator();
		// while (it.hasNext()) {
		// Map<String, Object> value = it.next();
		// String temp = format.format(value.get("advancedModelTime"));
		// value.put("advancedModelTime", temp);
		// }
		resultMap.put("total", recordsTotal);
		resultMap.put("recordsFiltered", recordsTotal);
		resultMap.put("rows", list);

		return resultMap;
	}

	@Override
	public Map<String, Object> selectUsersPager(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> sqlMap = new HashMap<String, Object>();
		response.setContentType("text/html;charset=utf-8");
		// String str = " 1=1 and user_imp = '" +
		// request.getSession().getAttribute("userId") + "'";
		// if
		// (request.getSession().getAttribute("roleId").equals("0084ae3f-3764-48d1-989c-0e9241e178a9"))
		// {
		String str = " 1=1";
		// }
		// 数据起始位置
		String start = request.getParameter("offset");
		// 数据长度
		String length = request.getParameter("limit");
		// 总记录数
		String recordsTotal = "0";
		// 获取数据库总记录数
		recordsTotal = userMapper.getUserCount(str) + "";
		sqlMap.put("start", Integer.parseInt(start));
		sqlMap.put("condition", " where" + str);
		sqlMap.put("length", Integer.parseInt(length));
		List<Map<String, Object>> list = userMapper.selectUsersPager(sqlMap);

		resultMap.put("total", recordsTotal);
		resultMap.put("recordsFiltered", recordsTotal);
		resultMap.put("rows", list);

		return resultMap;
	}

	@Override
	public Map<String, Object> updatePass(String oldPass, String newPass, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String userAccount = request.getSession().getAttribute("userAccount").toString();
		List<User> user_password = userMapper.selectByCondition(" USER_ACCOUNT='" + userAccount + "' AND USER_PASSWORD=md5('" + oldPass + "')  AND USER_STATUS NOT IN ('0') ");
		if (user_password != null && user_password.size() > 0) {
			User user = user_password.get(0);
			user.setUserPassword(newPass);
			Integer c = userMapper.updateByUser(user);
			resultMap.put("result", 0);
			if (c > 0) {
				resultMap.put("result", 1);
			}
		} else {
			resultMap.put("result", 2);
		}
		return resultMap;
	}

}
